<template>
  <div class="main_box" style="padding:10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ dataForm.promoteRuleId ? '编辑商户推广规则' : '新增商户推广规则' }}</h2>
        <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
      </div>
      <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="rules">
        <el-row>
          <el-form-item prop="ruleName" label="推广规则名称">
            <el-input type="text" v-model="dataForm.ruleName" placeholder="请输入推广规则名称"></el-input>
          </el-form-item>
          <el-form-item prop="ruleType" label="推广规则类型">
            <el-select v-model="dataForm.ruleType" clearable placeholder="请选择推广规则类型">
              <el-option :value="1" label="商户">
              </el-option>
              <el-option :value="2" label="平台">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="bussinessId" label="商户">
            <el-select v-model="dataForm.businessId" clearable filterable placeholder="请选择商户">
              <el-option v-for="item in businessList" :label="item.name" :value="item.id" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="remark" label="备注">
            <el-input type="textarea" v-model="dataForm.remark"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <div class="tit">
            <h2>推广规则明细</h2>
            <el-button icon="el-icon-plus" type="success" plain size="medium" circle @click="addBtn">
            </el-button>
          </div>
          <el-table :data="dataForm.list" max-height="800" style="width:calc(100vw - 280px);max-width: calc(100vw - 280px);margin-top: 10px;">
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button icon="el-icon-minus" type="danger" plain size="medium" @click="subBtn(scope.$index)" circle>
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="产品服务分类" width="250" align="center">
              <template slot-scope="scope">
                <el-cascader clearable filterable placeholder="请选择产品服务分类" v-model="scope.row.classifyIds"
                  :options="serverClassifyList" :props="{ checkStrictly: true, value: 'id', label: 'name' }">
                </el-cascader>
              </template>
            </el-table-column>
            <el-table-column label="产品编号" width="200" align="center">
              <template slot-scope="scope">
                <el-input placeholder="请输入产品编号" v-model="scope.row.goodsCode" clearable filterable>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="二级推广比例(%)" width="180" align="center">
              <template slot-scope="scope">
                <el-input placeholder="请输入二级推广比例" type="number" v-model="scope.row.firstDiscount"
                  @input="handleInputDiscount(scope.row,'firstDiscount')">

                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="一级推广比例(%)" width="180" align="center">
              <template slot-scope="scope">
                <el-input placeholder="请输入一级推广比例" type="number" v-model="scope.row.secondDiscount"
                  @input="handleInputDiscount(scope.row,'secondDiscount')">

                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="业推比例(%)" width="180" align="center">
              <template slot-scope="scope">
                <el-input placeholder="请输入业推比例" type="number" v-model="scope.row.thirdDiscount"
                  @input="handleInputDiscount(scope.row,'thirdDiscount')">

                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="二级推广金额(元)" width="180" align="center">
              <template slot-scope="scope">
                <el-input placeholder="请输入二级推广金额" type="number" v-model="scope.row.firstMoney"
                  @input="handleInputMoney(scope.row,'firstMoney')">
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="一级推广金额(元)" width="180" align="center">
              <template slot-scope="scope">
                <el-input placeholder="请输入一级推广金额" type="number" v-model="scope.row.secondMoney"
                  @input="handleInputMoney(scope.row,'secondMoney')">
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="业首推金额(元)" width="180" align="center">
              <template slot-scope="scope">
                <el-input placeholder="请输入业推金额" type="number" v-model="scope.row.thirdMoney"
                  @input="handleInputMoney(scope.row,'thirdMoney')">
                </el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button plain type="primary" @click="sureClick">保 存</el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import PromoteRuleApi from '@/api/operation/promoteRule.js';
import BeeperApi from "@/api/equip/beeper"
import BusinessApi from "@/api/business/business"
import ServerClassifyApi from "@/api/server/serverClassify"
export default {
  data() {
    return {
      dataForm: {
        promoteRuleId: "",
        ruleName: "",
        ruleType: 1,
        businessId:"",
        list: [
          {
            classifyIds: [],
            goodsCode: "",
            firstDiscount: "",
            secondDiscount: "",
            thirdDiscount:"",
            firstMoney: "",
            secondMoney: "",
            thirdMoney:"",
          }
        ],
        remark: "",
      },
      beeperList: [],
      businessList: [],
      serverClassifyList: [],
      goodsList: [],
      rules: {
        ruleName: [
          { required: true, message: "请输入规则名称", trigger: "focus" }
        ],
        ruleType: [
          { required: true, message: "请选择规则类型", trigger: "change" }
        ],
      }
    }
  },
  components: {
  },
  watch: {
    "dataForm.businessId":{
      handler(val){
        if(val){
          this.getServerClassifyList()
        }else{
          this.dataForm.list.forEach(item=>{
            item.classifyIds = []
          })
          this.serverClassifyList = []
        }
      },
      immediate:true
    }

  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      if (this.$route.query.id) {
        this.dataForm.promoteRuleId = this.$route.query.id
        this.getData()
      }
      this.getBusinessList()
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    getData() {
      PromoteRuleApi.getPromoteRule({
        id: this.dataForm.promoteRuleId
      }).then(res => {
        this.$Utils.bindingBean(this.dataForm, res.data)
        this.dataForm.list.forEach(item => {
          this.$set(item, 'classifyIds', [])
          item.parentClassifyId ? item.classifyIds.push(item.parentClassifyId) : ''
          item.serverClassifyId ? item.classifyIds.push(item.serverClassifyId) : ''
          item.thirdClassifyId ? item.classifyIds.push(item.thirdClassifyId) : ''
        })
      })

    },
    getBusinessList() {
      BusinessApi.listIdNameVo().then(res => {
        this.businessList = res.data
      })
    },
    getServerClassifyList() {
      ServerClassifyApi.listServerClassifyTree({businessId:this.dataForm.businessId}).then(res => {
        this.serverClassifyList = res.data
      })
    },
    addBtn() {
      this.dataForm.list.push({
        classifyIds: [],
        goodsCode: "",
        firstDiscount: "",
        secondDiscount: "",
        thirdDiscount:"",
        firstMoney: "",
        secondMoney: "",
        thirdMoney:"",
      })
    },
    subBtn(index) {
      this.dataForm.list.splice(index, 1)
    },
    handleInputDiscount(item,prop) {
      let val = item[prop]
      if (val < 0) {
        item[prop] = Math.abs(val)
      } else {
        item[prop] = parseFloat(parseFloat(val).toFixed(2)) || ""
      }

      if (val > 100) {
        item[prop] = ""
        this.$message.error("比例不可以超过100")
      }
    },
    handleInputMoney(item,prop) {
      let val = item[prop]
      if (val < 0) {
        item[prop] = Math.abs(val)
      }
    },

    checkData() {
      let list = this.dataForm.list
      let flag = false
      flag = list.some(item => {
        if (item.firtsDiscount===''&&item.secondDiscount===''&&item.thirdDiscount===''&&item.firstMoney===''&&item.secondMoney===''&&item.thirdMoney==='') {
          this.$message.error("推广比例与推广金额至少填写一项")
          return true
        }
        if (item.classifyIds.length == 0 && !item.goodsCode) {
          this.$message.error("产品服务分类、产品编号至少输入一个")
          return true
        }
      })
      if (flag) {
        return false
      }
      return true
    },

    sureClick() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          if (!this.checkData()) return
          this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {})
            .then(() => {
              if (this.dataForm.promoteRuleId) {
                this.editData();
              } else {
                this.addData();
              }
            });
        }
      })
    },
    addData() {
      let list = this.dataForm.list.map(item => {
        let classifyIds = item.classifyIds
        return {
          parentClassifyId: classifyIds[0] ? classifyIds[0] : "",
          serverClassifyId: classifyIds[1] ? classifyIds[1] : "",
          thirdClassifyId: classifyIds[2] ? classifyIds[2] : "",
          goodsCode: item.goodsCode,
          firstDiscount:item.firstDiscount,
          secondDiscount:item.secondDiscount,
          thirdDiscount:item.thirdDiscount,
          firstMoney:item.firstMoney,
          secondMoney:item.secondMoney,
          thirdMoney:item.thirdMoney,
        }
      })
      let param = {
        ruleName: this.dataForm.ruleName,
        ruleType: this.dataForm.ruleType,
        businessId:this.dataForm.businessId,
        list,
        remark: this.dataForm.remark,
      };

      PromoteRuleApi.addPromoteRule(param).then(res => {
        this.$Utils.notifySuccess()
        this.returnList();
      })
    },
    editData() {
      let list = this.dataForm.list.map(item => {
        let classifyIds = item.classifyIds
        return {
          parentClassifyId: classifyIds[0] ? classifyIds[0] : "",
          serverClassifyId: classifyIds[1] ? classifyIds[1] : "",
          thirdClassifyId: classifyIds[2] ? classifyIds[2] : "",
          goodsCode: item.goodsCode,
          firstDiscount:item.firstDiscount,
          secondDiscount:item.secondDiscount,
          thirdDiscount:item.thirdDiscount,
          firstMoney:item.firstMoney,
          secondMoney:item.secondMoney,
          thirdMoney:item.thirdMoney,
        }
      })
      let param = {
        promoteRuleId: this.dataForm.promoteRuleId,
        businessId:this.dataForm.businessId,
        ruleName: this.dataForm.ruleName,
        ruleType: this.dataForm.ruleType,
        list,
        remark: this.dataForm.remark,
      };
      PromoteRuleApi.editPromoteRule(param)
        .then(() => {
          this.$Utils.notifySuccess()
          this.returnList();
        })
    },
    returnList() {
      this.$store.dispatch('delView', this.$route);
      this.$router.push({ path: '/operation/promoteRuleManagement' });
    }
  },

}
</script>
<style lang="scss">
@import "@/assets/css/views/add.scss";
@import "@/assets/css/views/content.scss";
</style>

<style lang="scss" scoped>
.upload-img {
  &::v-deep .el-upload-dragger {
    display: flex;
    justify-content: space-around;
    align-items: center;

    .tip {
      padding-bottom: 30px;
    }
  }
}
</style>

